package org

import (
	"time"
	"strconv"
	"encoding/json"
	"dhfshop/models/org"
	"dhfshop/models/isv"
	"dhfshop/models/sale"
	"dhfshop/utils/helper"
	"github.com/astaxie/beego"
	"dhfshop/controllers/base"
	"dhfshop/service/nsqcli"
	"github.com/astaxie/beego/validation"
)

// 分销商门店管理
type StoreController struct {
	base.BaseController
}


func (this *StoreController) PubList() {
       query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	if len(query) == 0 {
	   this.ServeError("parameter is invalid")
	   return
	}
	if appId, ok := query["app_id"]; ok {
		custAccount, err := isv.GetCustAccountByAppId(appId)
		if err != nil {
		    this.ServeError(err.Error())
			return
		}
		delete(query, "app_id")
		query["partner_id"] = strconv.FormatInt(custAccount.PartnerId, 10)
	}
	var allowStoreId []int64
	l, cnt, err := org.GetAllStores(allowStoreId,query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
		r := struct {
		    TotalCount   int64     `json:"total_count"`
	        Store    []*org.Store `json:"store"`
	    }{TotalCount: cnt, Store: l}
	    this.Data["json"] = r
	this.ServeJSON()
}

func (this *StoreController) List() {
	curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	//curUserId := this.Ctx.Input.GetData("curUserId").(int)
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	  this.ServeError(err.Error())
	   return
	}
	if curRoleId == 2 {
	    query["partner_id"] = strconv.FormatInt(partnerId, 10)
	}else{
	
	}
	var allowStoreId []int64
	if this.CurrentUser != nil {
	    allowStoreId = this.CurrentUser.AllowStoreId
	}
	beego.Debug("Store allowStoreId:", allowStoreId)
	l, cnt, err := org.GetAllStores(allowStoreId,query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
		r := struct {
		    TotalCount   int64     `json:"total_count"`
	        Store    []*org.Store `json:"store"`
	    }{TotalCount: cnt, Store: l}
	    this.Data["json"] = r
	this.ServeJSON()
}

func (this *StoreController) Post() {
	var v org.Store
	valid := validation.Validation{}
	this.ParseForm(&v)
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	userId := int64(this.Ctx.Input.GetData("curUserId").(int))  
	valid.Required(v.PartnerId, "partner_id")
	valid.Required(v.Name, "name")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return	
	}
	storeId, err := org.AddStore(&v)
	if err != nil {
        this.ServeError(err.Error())
		return
    }
	sale.InitDefaultRootCid(v.PartnerId, storeId)
	sendCreateStoreMsg(v.PartnerId, storeId, userId)
	rsp := struct {
		StoreId    int64        `json:"store_id"`
	    Created   time.Time    `json:"created"`
	}{StoreId: storeId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *StoreController) Put() {
	v := org.Store{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"store_id","partner_id"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if ok, err := helper.Contains("is_main", updateFields); ok && err == nil {
	    oldStore, err := org.GetStoreById(v.StoreId)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		if ok := org.CheckMainStoreExist(oldStore.PartnerId); ok {
		    this.ServeError("主店已经存在")
			return
		}
	}
	if len(updateFields) > 0 {
		err := org.UpdateStoreById(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		    StoreId     int64       `json:"store_id"`
	        Modified   time.Time   `json:"modified"`
	    }{StoreId:v.StoreId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *StoreController) Delete() {
	store_id, _ := this.GetInt("store_id")
	storeId := int64(store_id)
	if err := org.DeleteStore(storeId); err == nil {
		rsp := struct {
		    StoreId     int64       `json:"store_id"`
	        Modified   time.Time   `json:"modified"`
	    }{StoreId:storeId, Modified:time.Now().UTC()}
	    this.Data["json"] = rsp
	} else {
	    this.ServeError(err.Error())
	}
	this.ServeJSON()
}

func sendCreateStoreMsg(partnerId, storeId, userId int64) {
	createStoreNsq := struct {
		PartnerId int64 `json:"partner_id"`
		StoreId   int64 `json:"store_id"`
		UserId    int64 `json:"user_id"`
		OrderTime int64 `json:"time"`
	}{}
	createStoreNsq.PartnerId = partnerId
	createStoreNsq.StoreId = storeId
	createStoreNsq.UserId = userId
	createStoreNsq.OrderTime = time.Now().UTC().Unix()
	if b, err := json.Marshal(createStoreNsq); err == nil {
		//beego.Debug("AddMsgEventsUser msg:", string(b))
		address := beego.AppConfig.String("NsqUrl")
		topic := "AddMsgEventsUser"
		if err = nsqcli.StartProducer(address, topic, b); err != nil {
			beego.Debug("StartProducer err:", err.Error())
		}
	}
}
